package com.edu.blockqueue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class ProdConsumer_BlockQueueDemo {

    public static void main(String[] args) throws InterruptedException {
        Resource resource = new Resource(new ArrayBlockingQueue(5));
        new Thread(()->{
            try {
                resource.prod();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(()->{
            try {
                resource.consume();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        Thread.sleep(10000);
        resource.setFlag(false);
    }
}

class Resource {
    private volatile boolean flag = true;
    AtomicInteger integer = new AtomicInteger();

    BlockingQueue<Object> blockingQueue;

    public Resource(BlockingQueue<Object> blockingQueue) {
        this.blockingQueue = blockingQueue;
        System.out.println("使用阻塞队列 " +blockingQueue.getClass());
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }

    public void prod() throws InterruptedException {
        String data;
        while (flag) {
            data = integer.getAndIncrement() + "";
            boolean offer = blockingQueue.offer(data, 2, TimeUnit.SECONDS);
            if (offer) {
                System.out.println("生产者 生产" + data + " 成功");
            } else {
                System.out.println("生产 生产" + data + " 失败");
            }
            Thread.sleep(1000);
        }
        System.out.println("老板叫停了生产，生产者退出");
    }

    public void consume() throws InterruptedException {
        while (flag) {
            String result = (String) blockingQueue.poll(2, TimeUnit.SECONDS);
            System.out.println("消费者 消费" + result + " 成功");
            Thread.sleep(1000);
        }
        System.out.println("老板叫停了生产，消费者退出");

    }

}
